<template>
  <div class="chart-content-wrapper" @mouseenter="mouseenter()" @mouseleave="mouseleave()">
    <!-- 头部筛选和标题 -->
    <top-filter :title="reportName" ref="topFilter" :isShowHelp="this.isShowHelp" :helpContent="this.helpMessage">
      <double-check-filter :isParentLinkChild="true" @confirmDoubleSelect="planAreaSelect" defaultText="统筹区"
                           :filter="filterN" type="planArea"></double-check-filter>
    </top-filter>
    <!-- 图标和结论 -->
    <div class="chart-container" v-show="isShowChart">
      <div id="pension-expenditure-analysis-year" class="chart-type1">
      </div>
      <Summarize :showSummarizeText="conclusion"></Summarize>
    </div>
  </div>
</template>

<script>

  import TopFilter from '../../last/filter/top-filter1'
  import DoubleCheckFilter from '../../last/filter/double-check-filter.vue'
  import Summarize from '../../last/summarize/summarize.vue'
  import {setChartHeight, loadingOpt, isJanuary} from '../../../assets/js/utils.js'
  import {getYearPensionExpenditure} from '../../../api/api'

  export default {
    components: {
      TopFilter,
      DoubleCheckFilter,
      Summarize
    },
    props: ['isChange', 'filter'],
    data () {
      return {
        reportName: '历年养老支出分析',
        filterN: JSON.parse(JSON.stringify(this.filter)),
        isShowChart: true,
        conclusion: '',
        areaCode: '',
        areaName: '',
        isShowHelp: false,
        helpMessage: ''
      }
    },
    mounted () {
      console.log('------------->mounted');
      this.initAreaData();
      this.initMyChart();
      this.resetChartHeight();
      this.getData();
    },
    activated () {
      console.log('------------->activated');
      if (!this.myChart) {
        this.initAreaData();
        this.initMyChart();
        this.resetChartHeight();
      }
      this.getData();
    },
    watch: {
      isChange () {
        setTimeout(() => {
          this.resetChartHeight();
        }, 111);
      }
    },
    methods: {
      resetChartHeight() {
        setChartHeight();
        setTimeout(()=>{
          if (this.myChart) {
            this.myChart.resize();
          }
        },1);
      },
      initAreaData () {
        let areaCode = [];
        let areaName = [];
        this.filter.nc.planArea.map((item, index) => {
          if (index > 0 && index <= 6) {
            areaCode.push(item.selectId)
            areaName.push(item.selectName);
          }
        });
        this.areaCode = areaCode.join(',');
        this.areaName = areaName.join('、');
      },
      initMyChart () {
        this.myChart = this.$echarts.init(document.getElementById('pension-expenditure-analysis-year'));
        let that = this;
        this.myChart.on('legendselectchanged', function (params) {
          let option = this.getOption();
          let select_key = Object.keys(params.selected);
          if (!params.selected[params.name]) {
            select_key.map(res => {
              option.legend[0].selected[res] = true;
            });
          } else {
            select_key.map(res => {
              option.legend[0].selected[res] = true;
            });
            option.legend[0].selected[params.name] = true;
          }
          let legend = [];
          that.myChart.dispatchAction({
            type: 'legendselectchanged',
            batch: legend
          });
          that.myChart.setOption(option);
        });
        // 点击事件
        this.myChart.off('click');
        this.myChart.on('click', function (params) {
          let hash = window.location.hash;
          if (params.componentSubType === 'bar') {
            let data = {
              hash,
              year: params.name,
              areaCode: that.areaCode,
              areaName: that.areaName
            };
            that.$router.push({
              path: `/decision/pension-analysis/pension-expenditure-analysis-year-detail`,
              query: data
            });
          }
        })
      },
      getData () {
        this.myChart.clear();
        this.myChart.showLoading(loadingOpt);

        getYearPensionExpenditure('pensionExpenditure/yearPensionExpenditure', this.areaCode).then(response => {
          let json = response.data;
          if (response.code == 0) {
            this.isShowChart = true;
            this.myChart.hideLoading();

            this.reportName = json.reportName;
            this.conclusion = json.reportConclusion;
            this.helpMessage = json.tip;
            this.isShowHelp = this.helpMessage.length > 0;

            this.drawLine(json)
          } else {
            this.isShowChart = false;
          }
        }).catch(res => {
          this.isShowChart = false;
        })
      },
      planAreaSelect (selectedIdArr, selectedNameArr) {
        // 统筹区选择
        this.areaCode = selectedIdArr.join(',');
        this.areaName = selectedNameArr.join('、');
        this.getData();
      },
      drawLine (json) {
        // 格式化负增长数据，为0时设为空
        json.negativeIncreaseQuotaList.map((item, index) => {
          if (item == 0) {
            json.negativeIncreaseQuotaList[index] = '';
          }
        });
        let boundaryNum = isJanuary();

        let barFormatter = function (params) {
          let str = json.positiveIncreaseQuotaList[params.dataIndex] > json.negativeIncreaseQuotaList[params.dataIndex] ? '增' : '减';
          return `<span style="color: #fff">养老支出</span></br>
                          <span style="color: #fff">年份: ${params.name}</span></br>
                          <span style="color: #fff">
                          支出金额: ${Number((json.yearlyTotalCostList[params.dataIndex] + json.positiveIncreaseQuotaList[params.dataIndex]).toFixed(2))}万元
                          </span></br>
                          <span>比去年${str}:</span>
                          <span style="color: #fff">${(json.positiveIncreaseQuotaList[params.dataIndex]
            > json.negativeIncreaseQuotaList[params.dataIndex])
            ? json.positiveIncreaseQuotaList[params.dataIndex]
            : json.negativeIncreaseQuotaList[params.dataIndex]}万元</span></br>
                          <span style="color: #67ffdb;
                                text-align: center;
                                line-height: 30px;height: 30px">单击图表查看详情</span>
                          `
        };
        let option = {
          grid: [//此参数可在一个dom中划分多个图表 可设置不同图表的位置
            {
              top: '10%',
              height: '14%',
              left: '60px',
              right: '60px',
              tooltip: {
                formatter: "{b}</br>{c}%" //给当前坐标系添加弹窗
              }
            },
            {
              top: '35%',
              height: '53%',
              left: '60px',
              right: '60px',
              tooltip: {
                show: false,
              }
            }
          ],
          legend: {
            top: '95%',
            left: 'center',
            icon: 'rect',
            itemWidth: 10,
            itemHeight: 10,
            itemGap: 20,
            selectedMode: false,
            tooltip: {
              show: true,
              formatter: function (params) {
                let txt = '';
                if (params.name == '增长额(正)') {
                  txt = '增长额(正)'
                } else if (params.name == '增长额(负)') {
                  txt = '增长额(负)'
                } else if (params.name == '养老支出金额') {
                  txt = '养老支出金额'
                }
                return txt;
              }
            },
            data: ['养老支出金额',
              '增长额(正)',
              '增长额(负)',
            ],
            textStyle: {
              color: '#fff'
            },
          },
          tooltip: {
            show: true,
            textStyle: {
              fontSize: 12
            }
          },
          xAxis: [
            {
              data: json.yearList,
              show: true,
              axisLine: {
                show: true, // 显示x轴坐标线并设置为虚线
                lineStyle: {
                  color: '#294363'
                }
              },
              axisTick: {
                show: false // 不显示x轴坐标的刻度
              },
              axisLabel: {
                show: false // 不显示x轴坐标数值
              }
            },
            {
              data: json.yearList,
              gridIndex: 1,
              axisLine: { // x轴的横线是否显示
                show: true,
                lineStyle: {
                  color: '#2a4565'
                }
              },
              axisTick: { // x轴的刻度短竖线是否显示
                show: false
              },
              axisLabel: {
                formatter: '{value}',
                textStyle: {
                  color: '#fff'
                }
              },
            }
          ],
          yAxis: [
            {
              splitLine: {
                show: false,
              },
              position: 'right',
              splitNumber: 2,
              axisLine: {
                show: false,
              },
              axisTick: {
                show: false
              },
              axisLabel: {
                formatter: '{value}',
                textStyle: {
                  color: '#fff'
                }
              },
            },
            {
              name: '单位 : 万元',
              nameTextStyle: {
                color: '#fff',
              },
              splitLine: {
                show: true,
                lineStyle: {
                  color: '#2a4565',
                  type: 'dashed',
                }
              },
              gridIndex: 1,
              axisLine: {
                show: true,
                lineStyle: {
                  color: '#2a4565',
                }
              },
              axisTick: {
                show: false
              },
              axisLabel: {
                formatter: '{value}',
                textStyle: {
                  color: '#fff'
                }
              },
            }
          ],
          visualMap: [
            {
              show: true,
              dimension: 0,
              seriesIndex: 0,
              left: 'center',
              top: 'top',
              itemWidth: 10,
              itemHeight: 10,
              orient: "horizontal",
              textStyle: {
                color: '#fff'
              },
              pieces: [
                {
                  lte: boundaryNum.preStart,
                  color: '#129cff',
                  symbol: 'circle',
                  name: '增长率（环比）',
                  label: '增长率（环比）',
                },
                {
                  gt: boundaryNum.preStart,
                  lte: boundaryNum.nextEnd,
                  symbol: 'circle',
                  color: '#67ffdb',
                  label: '增长率（同比）',
                  name: '增长率（同比）',
                }
              ],
            }
          ],
          series: [ // 折线
            {
              type: 'line',
              showSymbol: true,
              name: '增长率(环比/同比)',
              data: json.yearlyGrowthRateList,
              symbolSize: 10,
              tooltip: {
                show: true,
                formatter: function (params) {
                  return `<sapn style="color: #fff">增长率</sapn></br>
                          <span style="color: #fff">年份: ${params.name}</span></br>
                          <span style='color:#fff'>增长率: ${params.value}%</span>`
                }
              },
              label: {
                show: true,
                position: 'top',
                formatter: '{c}%',
                color: '#fff'
              }
            },
            {
              type: 'bar',
              name: '养老支出金额',
              stack: '总额',
              data: json.yearlyTotalCostList,
              color: '#ff6a93',
              barWidth: '40%',
              xAxisIndex: 1,
              yAxisIndex: 1,
              z: 2,
              tooltip: {
                show: true,
                formatter: barFormatter
              },
            },
            {
              type: 'bar',
              name: '增长额(正)',//此值与legend图例对应
              stack: '总额',
              color: '#ffd66a',
              data: json.positiveIncreaseQuotaList,

              label: {
                show: true,
                color: '#fff',
                position: 'top',
                formatter: function (params) {
                  var val = '';
                  let arr = json.yearlyTotalCostList;
                  arr.map((item, index) => {
                    if (params.dataIndex == index) {
                      if (Math.round((arr[index] + params.value) * 100) % 10 == 0) {
                        val = (arr[index] + params.value).toFixed(1)
                      } else if (Math.round((arr[index] + params.value) * 100) % 100 == 0) {
                        val = (arr[index] + params.value).toFixed(0)
                      } else {
                        val = (arr[index] + params.value).toFixed(2)
                      }
                    }
                  });

                  return Number(val);
                }
              },
              tooltip: {
                show: true,
                formatter: barFormatter
              },
              barWidth: '40%',
              xAxisIndex: 1,
              yAxisIndex: 1,
            },
            {
              type: 'bar',
              name: '增长额(负)',
              stack: '总额',
              showSymbol: false,
              data: json.negativeIncreaseQuotaList,
              z: 1,
              itemStyle: {
                color: '#263b5e',
              },
              tooltip: {
                show: true,
                formatter: barFormatter
              },
              barWidth: '40%',
              xAxisIndex: 1,
              yAxisIndex: 1
            }
          ],
        };

        this.myChart.setOption(option);
      },
      mouseenter () {
        this.$refs.topFilter._hideChartTitle()
      },
      mouseleave () {
        this.$refs.topFilter._showChartTitle()
      },
    }
  }
</script>

<style scoped>


</style>
